#include "UdpSocket.h"
#include "FloraLogger.h"
UdpSocket::UdpSocket(QObject *parent) : QUdpSocket(parent)
{
    connect(this, &QUdpSocket::readyRead, this, &UdpSocket::onReadyRead);
    connect(this, QOverload<QAbstractSocket::SocketError>::of(&QUdpSocket::error), this, &UdpSocket::handleError);
}

UdpSocket::~UdpSocket()
{
}

void UdpSocket::bindPort(quint16 port)
{
    if (bind(port)) {
        LOG_DEBUG<<(QString("Bound to port %1").arg(port));
    } else {
        LOG_DEBUG<<(QString("Failed to bind to port %1: %2").arg(port).arg(errorString()));
        emit errorOccurred(errorString());
    }
}

void UdpSocket::sendData(const QHostAddress &address, quint16 port, const QByteArray &data)
{
    qint64 bytesSent = writeDatagram(data, address, port);
    if (bytesSent != -1) {
        LOG_DEBUG<<(QString("Sent %1 bytes to %2:%3").arg(bytesSent).arg(address.toString()).arg(port));
    } else {
        LOG_DEBUG<<(QString("Failed to send data to %1:%2: %3").arg(address.toString()).arg(port).arg(errorString()));
        emit errorOccurred(errorString());
    }
}

void UdpSocket::onReadyRead()
{
    while (hasPendingDatagrams()) {
        QByteArray data;
        QHostAddress senderAddress;
        quint16 senderPort;

        data.resize(static_cast<int>(pendingDatagramSize()));
        readDatagram(data.data(), data.size(), &senderAddress, &senderPort);
        if(enable_debug){
            LOG_DEBUG<<(QString("Received %1 bytes from %2:%3 ").arg(data.size()).arg(senderAddress.toString()).arg(senderPort))<<data;
        }
        emit dataReceived(senderAddress, senderPort, data);
    }
}

void UdpSocket::handleError(QAbstractSocket::SocketError error)
{
    printDebugInfo(QString("Socket error: %1").arg(errorString()));
    emit errorOccurred(errorString());
}

void UdpSocket::printDebugInfo(const QString &message)
{
    qDebug()<< message;
}
